<template>
  <view>
    <f-navbar title="新增" navbarType="1"> </f-navbar>
    <view class="add-collection">
      <view class="form">
		<u--form labelPosition="left" labelWidth="100" 
		:model="form"
	  	:rules="rules"
		ref="uForm">
			<u-form-item
			  required
			  label="车辆类型"
			  prop="serviceType"
			  borderBottom
			>
			  <LSelect border="none"  v-model="form.serviceType" 
			  dataKey="dictLabel" dataValue="dictValue" :localdata="transportCarClass" ></LSelect>
			</u-form-item>
			<u-form-item
			  required
			  label="接收单位类型"
			  prop="startingStationType"
			  borderBottom
			>
			  <LSelect border="none"  v-model="form.startingStationType" 
			  dataKey="label" dataValue="value" :localdata="startingList" @change="startingSelect"></LSelect>
			</u-form-item>
			<u-form-item
			  required
			  label="接收单位"
			  prop="startingStationId"
			  borderBottom
			>
			  <LSelect border="none"  v-model="form.startingStationId"   v-if="form.startingStationType == 1"
			  dataKey="treatmentPlantName" dataValue="id" :localdata="reatmentplantAllList" ></LSelect>
			  <LSelect border="none"  v-model="form.startingStationId"   v-else
			  dataKey="sortingCenterName" dataValue="id" :localdata="sortingAllList" ></LSelect>
			</u-form-item>
			<u-form-item
			  required
			  label="中转站"
			  prop="recycleBinId"
			  borderBottom
			>
			  <LSelect border="none"  v-model="form.recycleBinId" 
			  dataKey="transferStationName" dataValue="id" :localdata="transferAllList"></LSelect>
			</u-form-item>
			<u-form-item
			  label="运输时间"
			  prop="transportationTime"
			  required
			  borderBottom
			   labelWidth="100"
			>
				<picker mode="date" :value="form.transportationTime" @change="transportationTimeChange">
				  <view class="box-item">
					<view v-if="form.transportationTime">{{
					  formatDate(form.transportationTime, "Y-m-d")
					}}</view>
					<view class="item-text" style="color: #c0c4cc" v-else>请选择</view>
				  </view>
				</picker>
			</u-form-item>
			<template v-if="form.serviceType == '1'">
				  <u-form-item
					label="收运油品"
					prop="oilId"
					borderBottom
					labelWidth="100"
				  >
					<LSelect border="none"  v-model="form.oilId" 
					dataKey="oilName" dataValue="id" :localdata="oilAllList" @change="myoilSelect"></LSelect>
				  </u-form-item>
				
				  <u-form-item
					label="油脂种类"
					prop="categoryId"
					borderBottom
					labelWidth="100"
				  >
					<LSelect border="none"  v-model="form.categoryId" 
					dataKey="typeName" dataValue="id" :localdata="categoryAllList"></LSelect>
				  </u-form-item>
			</template>
			<u-form-item
			  label="出厂总重量"
			  prop="appearanceWeight"
			  required
			  borderBottom
			  labelWidth="100"
			  
			>
			  <u--input
				v-model="form.appearanceWeight"
				placeholder="请输入"
				border="none"
			  ></u--input>
			</u-form-item>
			<u-form-item
			  label="车皮重量"
			  prop="carSkinWeight"
			  required
			  borderBottom
			  labelWidth="100"
			>
			  <u--input
				v-model="form.carSkinWeight"
				placeholder="请输入"
				border="none"
			  ></u--input>
			</u-form-item>
			<u-form-item
			  label="桶皮总重量"
			  prop="bucketSkinWeight"
			  required
			  labelWidth="100"
			  borderBottom
				v-if="form.serviceType == '2'"
			>
			  <u--input
				v-model="bucketSkinWeight"
				placeholder="自动计算,20KG/个"
				border="none"
				:disabled='true'
				disabledColor="#fff"
			  ></u--input>
			</u-form-item>
			<u-form-item
			  label="净重量"
			  prop="netWeight"
			  required
			  borderBottom
			  labelWidth="100"
			>
			  <u--input
				v-model="netWeight"
				placeholder="自动计算"
				border="none"
				:disabled='true'
				disabledColor="#fff"
			  ></u--input>
			</u-form-item>
		</u--form>
	  </view>
	  <template  v-if="form.serviceType == '2'">
	  	<view v-for="(item, index) of form.oilList" :key="index">
	  	  <view class="title flex-jb">
	  	    <view>信息{{ index + 1 }}</view>
	  	    <view v-if="index" class="delete" @click="delData(index)">删除</view>
	  	  </view>
	  	  <view class="form">
	  	    <u--form
	  	      labelPosition="left"
	  	      :model="item"
	  	      :rules="rules1"
	  	      :ref="`form${index}`"
	  	      labelWidth="100"
	  	    >
	  	      <u-form-item
	  	        required
	  	        label="收运油品"
	  	        prop="item.oilId"
	  	        borderBottom
	  	      >
	  	        <LSelect border="none"  v-model="item.oilId" dataKey="oilName" dataValue="id" :localdata="oilAllList" @change="oilSelect"  :isIndex="true"  :indexNum="index"></LSelect>
	  	      </u-form-item>
	  	      <u-form-item required label="油脂种类" prop="item.categoryId" borderBottom>
	  					<!-- categoryAllList -->
	  	        <LSelect border="none"  v-model="item.categoryId" dataKey="typeName" dataValue="id" :localdata="item.categoryAllList" ></LSelect>
	  	        
	  	      </u-form-item>
	  	      <u-form-item
	  	        label="桶数(桶)"
	  	        required
	  	        prop="item.barrelsNumber"
	  	        borderBottom
	  	      >
	  	        <u--input
	  	          v-model="item.barrelsNumber"
	  	          border="none"
	  	          placeholder="请输入"
	  	        ></u--input>
	  	      </u-form-item>
	  	      <u-form-item
	  	        label="总重量（kg）"
	  	        prop="item.appearanceWeight"
				required
	  	        borderBottom
	  	        labelWidth="120"
	  	      >
	  	        <u--input
	  	          v-model="item.appearanceWeight"
	  	          border="none"
	  	          placeholder="请输入"
	  	        ></u--input>
				<u-button slot="right" type="success" size="mini">获取数据</u-button>
	  	      </u-form-item>
			  <u-form-item
			    label="车皮重量（kg）"
			    prop="item.carSkinWeight"
				required
			    borderBottom
			    labelWidth="120"
			  >
			    <u--input
			      v-model="item.carSkinWeight"
			      border="none"
			      placeholder="请输入"
			    ></u--input>
				<u-button slot="right" type="success" size="mini">获取数据</u-button>
			  </u-form-item>
			  <u-form-item
			    label="净重量（kg）"
			    prop="item.netWeight"
				required
			    borderBottom
			    labelWidth="120"
			  >
			    <u--input
			      v-model="item.netWeight"
				  placeholder="自动计算"
				  border="none"
				  :disabled='true'
				  disabledColor="#fff"
			    ></u--input>
			  </u-form-item>
	  	    </u--form>
	  	  </view>
	  	</view>
	  </template>
      
      <view class="button">
        <view class="button2" @click="addData"  v-if="form.serviceType == '2' && form.oilList.length < 3">添加</view>
        <view class="button1" @click="submit">确认提交</view>
      </view>
    </view>
  </view>
</template>

<script>
import { 
	user_sign_allList,
	category_allList,
	
	oil_allList,
	listAllTreatmentplant,
	listAllSorting_center,
	listAllTransfer_station,
	addLn_receipt_shipment_order,
	transportationRecordsDetails
	

} from "@/api/transport.js";
import LSelect from "@/components/LSelect";
export default {
	components: {
		LSelect
	},
  data() {
    return {
		transportCarClass:[], //车辆类型
		// 接收单位类型
		startingList:[
			{
				value:'0',
				label:'预处理厂'
			},
			{
				value:'1',
				label:'处理厂'
			}
		],
		
		reatmentplantAllList:[],//处理厂
		sortingAllList:[],//预处理厂
		transferAllList:[],//中转站
		user_signAllList: [], //排放单位列表
		oilAllList:[], //油品列表
		categoryAllList:[],//种类列表
		  // 表单校验
		rules: {
			serviceType: { required: true, message: "请选择车辆类型", trigger: ['blur'] },  
			startingStationType: { required: true, message: "请选择接收单位类型", trigger: ['blur'] },      
			startingStationId: { required: true, message: "请选择接收单位",trigger: ['blur'] },        
			recycleBinId: { required: true, message: "请选择中转站", trigger: ['blur'] },        
			transportationTime: { required: true, message: "请选择运输日期", trigger: ['blur'] },    
			 // oilId: { required: true, message: "请选择收运油品", trigger: ['blur'] },     
			 // categoryId: { required: true, message: "请选择油脂种类", trigger: ['blur'] },     
			appearanceWeight: { required: true, message: "请输入出厂总重量", trigger: ['blur']},        
			carSkinWeight: { required: true, message: "请输入车皮重量", trigger: ['blur'] },    
		},
		rules1:{},
		form: {
			serviceType:1,
			transportationTime:'',
			oilList: [
				{
				  oilId: null, //油品id
				  categoryId: null, //油脂种类ID
				  barrelsNumber:null,//桶@change数
				  weight:null,//预估重量
				  appearanceWeight:null,//"出场总重量
				  carSkinWeight:null, //车皮重量
				  netWeight:null, //净重量
				  categoryAllList:[]
				},
			],
		},
    };
  },
  watch:{
	'form.oilList':{
		handler(newVal, oldVal) {
		  console.log('Form array changed:', newVal);
			newVal.forEach((item,index) => {
				if(index == 0){
					// 信息一净重量=总重量-车皮重量-桶数*20kg
					item.netWeight = item.appearanceWeight - item.carSkinWeight - (Number(item.barrelsNumber) * 20)
					item.weight = item.netWeight
				}if(index == 1){
					// 信息二净重量=信息二的总重量-信息一的总重量—信息二的桶数*20kg
					item.netWeight = item.appearanceWeight - this.form.oilList[0].appearanceWeight - (Number(item.barrelsNumber) * 20)
					item.weight = item.netWeight
				}if(index == 2){
					// 信息三净重量=信息三的总重量-信息二的总重量—信息三的桶数*20kg
					item.netWeight = item.appearanceWeight - this.form.oilList[1].appearanceWeight - (Number(item.barrelsNumber) * 20)
					item.weight = item.netWeight
				}
			});
		},
		deep: true // 启用深度监听，以监听数组内对象的变化
    }
  },
  computed:{
	  netWeight(){
		// 罐
		if(this.form.serviceType == '1'){
		  let weight = this.form.appearanceWeight - this.form.carSkinWeight
		  this.form.netWeight =  weight
		  return weight
		}
		// 挂车
		if(this.form.serviceType == '2'){
		  let num = 0
		   this.form.oilList.forEach(item => {
		  		num += Number(item.netWeight)
		   });
		 //  this.form.oilList.forEach(item => {
			// num += Number(item.barrelsNumber)
		 //  });
		 //  // 桶皮重量
		 //  let bucketSkinWeight = num * 20
		 //  // 净重
		 //  let weight = this.form.appearanceWeight - this.form.carSkinWeight - bucketSkinWeight
		  this.form.netWeight =  num        
		  return num
		}
	  },
	  // 桶皮重量 20/个
	  bucketSkinWeight(){
		let num = 0
		this.form.oilList.forEach(item => {
		  num += Number(item.barrelsNumber)
		});
		let allWeight = num * 20
		this.form.bucketSkinWeight = allWeight
		return allWeight
		
	  }

  },
  onLoad(option) {
  	if(option.id){
  		this.getDetails(option.id)
  	}
  },
  onShow() {
	  this.getData()
	this.getTransferAllList()
	this.getOilList()
  },
  methods: {
	getDetails(id) {
		transportationRecordsDetails(id).then(res => {
			this.form = res.data
		})
	},
	  // transport_car_class
	async getData() {
		this.transportCarClass = await this.getDictionaryData("transport_car_class");
	},
	transportationTimeChange(e) {
      this.form.transportationTime = e.detail.value ;
    },
	// 查询所有中转站
	getTransferAllList(){
		listAllTransfer_station().then((response) => {
		this.transferAllList = response.data;
	  });
	},
	// 根据接收单位类型查询接收单位列表 （预处理厂，处理厂） 0预处理厂1处理厂
	startingSelect(value){
		if(value == 1){
			listAllTreatmentplant().then((response) => {
				this.reatmentplantAllList = response.data;
			});
		}else{
			listAllSorting_center().then((response) => {
				this.sortingAllList = response.data;
			});
		}
	},
	// 油品列表
	getOilList() {
	  oil_allList().then((response) => {
		this.oilAllList = response.data;
	  });
	},
	 // 选择油品，根据油品获取种类
	 myoilSelect(id){
		 this.form.categoryId = ''
	 	category_allList({
	 		oilId:id
	 	}).then((response) => {
	 	this.categoryAllList = response.data;
	   });
	 },
	 oilSelect(e){
	 	console.log('oilSelect',e)
	 	let index = e.index
	 	category_allList({
	 		oilId:e.id
	 	}).then((response) => {
	 		// this.categoryAllList = response.data;
	 		let isTrue = response.data.find(item => item.id == this.form.oilList[index].categoryId)
	 		if(!isTrue){
	 		  this.form.oilList[index].categoryId = ''
	 		}
	 		this.form.oilList[index].categoryAllList = [...response.data];
	 		// 此处是更新视图操作
	 		let newData = this.form.oilList[index]
	 		this.form.oilList.splice(index,1,newData)
	   });
	 },
    addData() {
		let arr =   {
            oilId: null, //油品id
            categoryId: null, //油脂种类ID
            barrelsNumber:null,//桶@change数
            weight:null,//重量
            appearanceWeight:null,//"出场总重量
            carSkinWeight:null, //车皮重量
            netWeight:null, //净重量
			categoryAllList:[]
          }
      this.form.oilList.push(arr);
    },
    delData(index) {
		this.form.oilList.splice(index, 1);
    },
	submit(){
		console.log(this.form.startingStationType);
		this.$refs.uForm.validate().then((res) => {
			if(this.form.serviceType == '2'){
				for(let i = 0; i < this.form.oilList.length; i++){
					const item = this.form.oilList[i]
					if(!item.oilId){
						uni.$u.toast('请选择收运油品');
						return false
					}
					if(!item.categoryId){
						uni.$u.toast('请选择油脂种类');
						return false
					}
					if(!item.barrelsNumber){
						uni.$u.toast('请输入桶数');
						return false
					}
					if(!item.appearanceWeight){
						uni.$u.toast('请输入总重量');
						return false
					}
					if(!item.carSkinWeight){
						uni.$u.toast('请输入车皮重量');
						return false
					}
				}
			}
		  addLn_receipt_shipment_order(this.form).then(res => {
		  	uni.$u.toast('添加成功');
		  	this.goLink('','back')
		  })
		});
		
	}
  },
};
</script>

<style lang="less" scoped>
.add-collection {
  padding: 30rpx 30rpx 0 30rpx;
  .title {
    font-size: 30rpx;
    color: #000;
    margin: 28rpx 0 20rpx 0;
    .delete {
      color: #138e57;
    }
  }
  .form {
    padding: 0 30rpx;
    background: #ffffff;
    border-radius: 16rpx;
	.btn{
		padding: 20rpx 30rpx;
		background: linear-gradient(83deg, #48b453 0%, #2c9f79 100%);
	}
  }
  .button {
    margin: 0 40rpx;
    padding: 80rpx 0;
  }
  .button1 {
    color: #ffffff;
    margin-top: 30rpx;
    background: linear-gradient(83deg, #48b453 0%, #2c9f79 100%);
  }
  .button2 {
    color: #138e57;
    border: 2rpx solid #138e57;
  }
  .button1,
  .button2 {
    padding: 24rpx;
    text-align: center;
    border-radius: 200rpx;
    font-size: 32rpx;
  }
}
</style>
